package com.css.fxfzypg.modules.resultManagement.reportManagement.service.Impl;

import com.css.fxfzypg.common.utils.BeanUtil;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.repository.IntensityRelationRepository;
import com.css.fxfzypg.modules.SettingSeismic.vo.SettingSeismicDetailsVO;
import com.css.fxfzypg.modules.model.entity.*;
import com.css.fxfzypg.modules.model.service.*;
import com.css.fxfzypg.modules.preAssessResult.service.PreAssessResultService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.ResultTable;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.ReportDataService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.ypg.YpgRatio;
import com.css.fxfzypg.modules.resultupload.repository.ResultRepository;
import com.css.fxfzypg.modules.resultupload.repository.ResultTotalRepository;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultMainEntity;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Distinct;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportDataServiceImpl implements ReportDataService {
    @Resource
    ResultTotalRepository resultTotalRepository;
    @Resource
    PreAssessResultService preAssessResultService;
    @Resource
    IntensityRelationRepository intensityRelationRepository;
    @Resource
    IntensityAttenuationService intensityAttenuationService;
    @Resource
    CasualtyService casualtyService;
    @Resource
    EconomicLossesService economicLossesService;
    @Resource
    RescueForceService rescueForceService;
    @Resource
    MaterialService materialService;
    @Resource
    ResultRepository resultRepository;
    @Resource
    PreAssessTaskRepository preAssessTaskRepository;
    @Resource
    ResettlementPersonnelService resettlementPersonnelService;
    @Resource
    SysAreaService sysAreaService;

    @Override
    public Map<String, Object> getReportData(String id,List<String> taskIdList,StringBuilder msg) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        List<ResultMainEntity> resultTotal = new ArrayList<>();
        List<SettingSeismicDetailsVO> list = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(taskIdList)){
            //查询子任务的数据
            List<ResultMainEntity> tempResult =  resultTotalRepository.getResultTotalByTaskId(taskIdList);
            if(PlatformObjectUtils.isNotEmpty(tempResult)){
                resultTotal.addAll(tempResult);
            }
            List<SettingSeismicDetailsVO> stempResult = preAssessResultService.setEarthquakeCensus(taskIdList);
            if(PlatformObjectUtils.isNotEmpty(stempResult)){
                list.addAll(stempResult);
            }
        }else{
            resultTotal = resultTotalRepository.getResultTotalByTaskId(id);
            list = preAssessResultService.setEarthquakeCensus(id);
        }

        ArrayList<String> magnitudes = new ArrayList<>();
        for (ResultMainEntity resultMainEntity : resultTotal) {
            BigDecimal magnitude = resultMainEntity.getMagnitude();
            magnitudes.add(magnitude.toString());
        }
        magnitudes = new ArrayList<>(new TreeSet<String>(magnitudes));

        StringBuilder stringBuilder = new StringBuilder();
        int i = 0;
        for (String magnitude : magnitudes) {
            i++;
            stringBuilder.append(magnitude);
            if (i != magnitudes.size()) {
                stringBuilder.append("、");
            } else {
                stringBuilder.append(" ");
            }
        }
        int size = magnitudes.size();
        //设置地震各个震级
        map.put("magnitudes", stringBuilder.toString());
        //设置地震震级个数
        map.put("earthSum", numberToChinese(size));

        List<Map<String, Object>> lists = new ArrayList<>();
        for (SettingSeismicDetailsVO settingSeismicDetailsVO : list) {
            int faultNum = settingSeismicDetailsVO.getFaultNum();
            BigDecimal longitude = settingSeismicDetailsVO.getLongitude().setScale(2,BigDecimal.ROUND_HALF_UP);
            BigDecimal latitude = settingSeismicDetailsVO.getLatitude().setScale(2,BigDecimal.ROUND_HALF_UP);
            String macroPosition = settingSeismicDetailsVO.getMacroPosition();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("faultNum", String.valueOf(faultNum));
            map1.put("longitude", String.valueOf(longitude));
            map1.put("latitude", String.valueOf(latitude));
            map1.put("macroPosition", macroPosition);
            lists.add(map1);
        }
        //工作区设定地震位置表格
        map.put("earthtable", lists);
        //烈度衰减模型X
        List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(id);
        List<String> modelNameList = new ArrayList<>();
        List<YpgRatio> ratioList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        Set<String> set = new HashSet<>();
        if (subTask.size() == 0) {
            PreAssessTaskEntity byId = preAssessTaskRepository.findById(id);
            String taskDistrict = byId.getTaskDistrict();
            if(taskDistrict.contains("、")){
                String[] split = taskDistrict.split("、");
                for(String str:split){
                    if(str.contains("-")){
                        String[] split1 = str.split("-");
                        set.add(split1[0]);
                    }else{
                        set.add(str);
                    }
                }
            }
            if(taskDistrict.contains("-")){
                String[] split1 = taskDistrict.split("-");
                set.add(split1[0]);
            }
            SeismicIntensityRelation seismicIntensity = intensityRelationRepository.getByTaskId(id);
            if (PlatformObjectUtils.isNotEmpty(seismicIntensity.getModel1Id())) {
                IntensityAttenuation model1 = intensityAttenuationService.getModel1ById(seismicIntensity.getModel1Id());
                if(model1!=null){
                    if ("0".equals(model1.getType())) {
                        StringBuilder builder = new StringBuilder();
                        String a = "Ia = " + model1.getLongRatio1() + "+" + model1.getLongRatio2() + "M -" + model1.getLongRatio3() + model1.getLongSymbol() + "(Ra+" + model1.getLongRatio4() + ")";
                        String b = "Ib = " + model1.getShortRatio1() + "+" + model1.getShortRatio2() + "M -" + model1.getShortRatio3() + model1.getShortSymbol() + "(Rb+" + model1.getShortRatio4() + ")";
                        builder.append("            "+a+"\n");
                        builder.append("            "+b+"\n");
                        builder.append("    其中Ia、Ib分别为长短轴烈度，M为震级，Ra、Rb分别为烈度为 I 时长、短半轴的长度。\n");
                        map.put("intensity", builder.toString());
                    }
                    if ("1".equals(model1.getType())) {
                        StringBuilder builder = new StringBuilder();
                        String a = "Ia = " + model1.getLongRatio1() + "+" + model1.getLongRatio2() + "M -" + model1.getLongRatio3() + model1.getLongSymbol() + "(Ra+" + model1.getLongRatio4() + ")";
                        String b = "Ib = " + model1.getShortRatio1() + "+" + model1.getShortRatio2() + "M -" + model1.getShortRatio3() + model1.getShortSymbol() + "(Rb+" + model1.getShortRatio4() + ")";
                        String c = "M = "+model1.getFormulaRatio1()+ "+" +model1.getFormulaRatio2()+ "* log(SRL)";
                        String d = String.valueOf(model1.getScale());
                        builder.append("当震级小于7.0级时使用椭圆衰减模型，当震级大于等于7.0级时使用破裂尺度公式计算出长轴长度，根据长短轴比例计算出短轴长度。\n");
                        builder.append("    1、当震级小于7.0级时使用椭圆衰减模型\n");
                        builder.append("                "+a+"\n");
                        builder.append("                "+b+"\n");
                        builder.append("    其中Ia、Ib分别为长短轴烈度，M为震级，Ra、Rb分别为烈度为 I 时长、短半轴的长度。\n");
                        builder.append("    2、当震级大于等于7.0级时使用破裂尺度公式计算出长轴长度，根据长短轴比例计算出短轴长度\n");
                        builder.append("    破裂尺度公式:\n");
                        builder.append("                  "+c+"\n");
                        builder.append("    SRL为地表破裂带长度\n");
                        builder.append("    最终的长轴长度=Ra * 2 +SRL\n");
                        builder.append("    长短轴比例:"+d+"\n");
                        map.put("intensity", builder.toString());
                    }
                }
            }else {
                map.put("intensity", "");
            }
            //人员伤亡评估模型
            if (PlatformObjectUtils.isNotEmpty(seismicIntensity.getModel2Id())) {
                Casualty model2 = casualtyService.getModel1ById(seismicIntensity.getModel2Id());
                BigDecimal deathNumber = model2.getDeathNumber();
                BigDecimal injuries = model2.getInjuries();
                //Si 为人口变化特征修正值
                map.put("deathNumber", String.valueOf(deathNumber));
                //C为受伤人数与死亡人数的比例
                map.put("injuries", String.valueOf(injuries));
            } else {
                map.put("deathNumber", "");
                map.put("injuries", "");
            }

            //经济损失评估模型
            if (PlatformObjectUtils.isNotEmpty(seismicIntensity.getModel3Id())) {
                EconomicLosses model3 = economicLossesService.getModel1ById(seismicIntensity.getModel3Id());
                if(StringUtils.isNotBlank(model3.getProvince())){
                    String areaName = sysAreaService.getAreaNameByAreaId(model3.getProvince());
                    model3.setProvince(areaName);
                }
                //建筑物结构经济损失评估调整参数
                map.put("structureLossess", String.valueOf(model3.getStructureLossess()));
                //建筑物室内财产经济损失评估调整参数
                map.put("indoorLossess", String.valueOf(model3.getIndoorLossess()));
                //生命线经济损失评估,Bm为建筑物经济损失在总经济损失中所占百分比
                map.put("liferatioBm", String.valueOf(model3.getLifeRatio1()));
                //生命线经济损失评估,Lm为生命线经济损失在总经济损失中所占百分比
                map.put("liferatioLm", String.valueOf(model3.getLifeRatio2()));
                //其他经济损失评估,Bm为建筑物经济损失在总经济损失中所占百分比
                map.put("otherRatioBm", String.valueOf(model3.getOtherRatio1()));
                //其他经济损失评估,Om为其他经济损失在总经济损失中所占百分比
                map.put("otherRatioOm", String.valueOf(model3.getOtherRatio2()));
                List<Map<String, Object>> destorytable = toArray1(model3);
                //建筑物损失比矩阵表格
                map.put("destorytable", destorytable);
            } else {
                map.put("structureLossess", "");
                map.put("indoorLossess", "");
                map.put("liferatioBm", "");
                map.put("liferatioLm", "");
                map.put("otherRatioBm", "");
                map.put("otherRatioOm", "");
            }

            //需紧急安置人数模型
            if (PlatformObjectUtils.isNotEmpty(seismicIntensity.getModel4Id())) {
                String model4Type = seismicIntensity.getModel4Type();
                if ("1".equals(model4Type)) {
                    modelNameList.add("需紧急安置人数默认模型");
                }
                if ("2".equals(model4Type)) {
                    ResettlementPersonnel model = resettlementPersonnelService.getModel1ById(seismicIntensity.getModel4Id());
                    modelNameList.add("模型管理中的模型");
                    if(set.size()>0){
                        sb.append(String.join(",",set));
                    }
                    YpgRatio ratio = new YpgRatio();
                    ratio.setIntensity("需紧急安置人数占人口比例");
                    ratio.setProvince(sb.toString());
                    ratio.setResettlementRatio1(model.getRatio1().toString());
                    ratio.setResettlementRatio2(model.getRatio2().toString());
                    ratio.setResettlementRatio3(model.getRatio3().toString());
                    ratio.setResettlementRatio4(model.getRatio4().toString());
                    ratioList.add(ratio);
                }
            }
            if(!modelNameList.contains("需紧急安置人数默认模型")){
                map.put("modelName1", "需紧急安置人数默认模型(需删除)");
            }else{
                map.put("modelName1", "需紧急安置人数默认模型");
            }
            if(!modelNameList.contains("模型管理中的模型")){
                map.put("modelName2", "模型管理中的模型(需删除)");
            }else{
                map.put("modelName2", "模型管理中的模型");
            }
            //救援队伍,医务人员需求模型
            if (PlatformObjectUtils.isNotEmpty(seismicIntensity.getModel5Id())) {
                RescueForceEntity rescueForceModel = rescueForceService.getModel1ById(seismicIntensity.getModel5Id());
                map.put("modelNumber1", String.valueOf(rescueForceModel.getRescueRanksModelNumber1()));
                map.put("modelNumber2", String.valueOf(rescueForceModel.getRescueRanksModelNumber2()));
                map.put("modelNumber3", String.valueOf(rescueForceModel.getRescueRanksModelNumber3()));
                map.put("modelNumber4", String.valueOf(rescueForceModel.getMajorRescueForceProportion()));
                map.put("modelNumber5", String.valueOf(rescueForceModel.getPopularRescueForceProportion()));
                map.put("modelNumber6", String.valueOf(rescueForceModel.getSocietyOtherForceProportion()));
                map.put("modelNumber7", String.valueOf(rescueForceModel.getMedicalStaffModelNumber()));
                map.put("modelNumber8", String.valueOf(rescueForceModel.getDoctorProportion()));
                map.put("modelNumber9", String.valueOf(rescueForceModel.getNurseProportion()));
                map.put("modelNumber10", String.valueOf(rescueForceModel.getPsychologistProportion()));
            } else {
                msg.append(byId.getTaskName()).append("的救援队伍,医务人员需求模型信息未维护。");
                map.put("modelNumber1", "");
                map.put("modelNumber2", "");
                map.put("modelNumber3", "");
                map.put("modelNumber4", "");
                map.put("modelNumber5", "");
                map.put("modelNumber6", "");
                map.put("modelNumber7", "");
                map.put("modelNumber8", "");
                map.put("modelNumber9", "");
                map.put("modelNumber10", "");
            }

            //救援物资,医疗资源需求模型sss

            if (PlatformObjectUtils.isNotEmpty(seismicIntensity.getModel6Id())) {
                Material material = materialService.getModel1ById(seismicIntensity.getModel6Id());
                map.put("modelNumber11", String.valueOf(material.getRatio1()));
                map.put("modelNumber12", String.valueOf(material.getRatio2()));
                map.put("modelNumber13", String.valueOf(material.getRatio6()));
                map.put("modelNumber14", String.valueOf(material.getRatio7()));
                map.put("modelNumber15", String.valueOf(material.getRatio8()));
                map.put("modelNumber16", String.valueOf(material.getRatio9()));
                map.put("modelNumber17", String.valueOf(material.getRatio10()));
                BigDecimal tempVal = material.getRatio11().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_DOWN);
                map.put("modelNumber18", String.valueOf(tempVal)+"%");
                tempVal = material.getRatio12().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_DOWN);
                map.put("modelNumber19", String.valueOf(tempVal)+"%");
                map.put("modelNumber20", String.valueOf(material.getRatio13()));
                map.put("modelNumber21", String.valueOf(material.getRatio14()));
                map.put("modelNumber22", String.valueOf(material.getRatio15()));
            } else {
                msg.append(byId.getTaskName()).append("的救援物资,医疗资源需求模型信息未维护。");
                map.put("modelNumber11", "");
                map.put("modelNumber12", "");
                map.put("modelNumber13", "");
                map.put("modelNumber14", "");
                map.put("modelNumber15", "");
                map.put("modelNumber16", "");
                map.put("modelNumber17", "");
                map.put("modelNumber18", "");
                map.put("modelNumber19", "");
                map.put("modelNumber20", "");
                map.put("modelNumber21", "");
                map.put("modelNumber22", "");
            }
        }else {
            //没有破裂尺度
            List<PreAssessTaskEntity> preAssessTaskEntitys1 = new ArrayList<>();
            //有破裂尺度
            List<PreAssessTaskEntity> preAssessTaskEntitys2 = new ArrayList<>();
            StringBuilder deathNumberBuild = new StringBuilder();
            StringBuilder injuriesBuild = new StringBuilder();
            StringBuilder structureLossessBuild = new StringBuilder();
            StringBuilder indoorLossessBuild = new StringBuilder();
            StringBuilder liferatioBmBuild = new StringBuilder();
            StringBuilder liferatioLmBuild = new StringBuilder();
            StringBuilder otherRatioBmBuild = new StringBuilder();
            StringBuilder otherRatioOmBuild = new StringBuilder();
            StringBuilder modelNumber1Build = new StringBuilder();
            StringBuilder modelNumber2Build = new StringBuilder();
            StringBuilder modelNumber3Build = new StringBuilder();
            StringBuilder modelNumber4Build = new StringBuilder();
            StringBuilder modelNumber5Build = new StringBuilder();
            StringBuilder modelNumber6Build = new StringBuilder();
            StringBuilder modelNumber7Build = new StringBuilder();
            StringBuilder modelNumber8Build = new StringBuilder();
            StringBuilder modelNumber9Build = new StringBuilder();
            StringBuilder modelNumber10Build = new StringBuilder();
            StringBuilder modelNumber11Build = new StringBuilder();
            StringBuilder modelNumber12Build = new StringBuilder();
            StringBuilder modelNumber13Build = new StringBuilder();
            StringBuilder modelNumber14Build = new StringBuilder();
            StringBuilder modelNumber15Build = new StringBuilder();
            StringBuilder modelNumber16Build = new StringBuilder();
            StringBuilder modelNumber17Build = new StringBuilder();
            StringBuilder modelNumber18Build = new StringBuilder();
            StringBuilder modelNumber19Build = new StringBuilder();
            StringBuilder modelNumber20Build = new StringBuilder();
            StringBuilder modelNumber21Build = new StringBuilder();
            StringBuilder modelNumber22Build = new StringBuilder();

            List<Map<String, Object>> allDestorytable = new ArrayList<>();
            List<String> provinceList = new ArrayList<>();
            List<String> model4TypeList = new ArrayList<>();
            for (PreAssessTaskEntity preAssessTaskEntity : subTask) {
                String taskDistrict = preAssessTaskEntity.getTaskDistrict();
                if(taskDistrict.contains("-")){
                    taskDistrict = taskDistrict.split("-")[0];
                }
                SeismicIntensityRelation intensity = intensityRelationRepository.getByTaskId(preAssessTaskEntity.getId());
                if(PlatformObjectUtils.isNotEmpty(intensity.getModel1Id())){
                    IntensityAttenuation model1 = intensityAttenuationService.getModel1ById(intensity.getModel1Id());
                    if(model1!=null){
                        if ("0".equals(model1.getType())){
                            preAssessTaskEntitys1.add(preAssessTaskEntity);
                        }
                        if ("1".equals(model1.getType())){
                            preAssessTaskEntitys2.add(preAssessTaskEntity);
                        }
                    }
                }
                //人员伤亡评估模型
                if (PlatformObjectUtils.isNotEmpty(intensity.getModel2Id())) {
                    Casualty model2 = casualtyService.getModel1ById(intensity.getModel2Id());
                    //Si 为人口变化特征修正值
                    BigDecimal deathNumber = model2.getDeathNumber();
                    //C为受伤人数与死亡人数的比例
                    BigDecimal injuries = model2.getInjuries();
                    if(!provinceList.contains(taskDistrict)){
                        deathNumberBuild.append(taskDistrict).append(":").append(deathNumber).append("、");
                        injuriesBuild.append(taskDistrict).append(":").append(injuries).append("、");
                    }
                }

                //经济损失评估模型
                if (PlatformObjectUtils.isNotEmpty(intensity.getModel3Id())) {
                    EconomicLosses model3 = economicLossesService.getModel1ById(intensity.getModel3Id());
                    model3.setProvince(taskDistrict);
                    //建筑物结构经济损失评估调整参数
                    if(!provinceList.contains(taskDistrict)){
                        structureLossessBuild.append(taskDistrict).append(":").append(model3.getStructureLossess()).append("、");
                        indoorLossessBuild.append(taskDistrict).append(":").append(model3.getIndoorLossess()).append("、");
                        liferatioBmBuild.append(taskDistrict).append(":").append(model3.getLifeRatio1()).append("、");
                        liferatioLmBuild.append(taskDistrict).append(":").append(model3.getLifeRatio2()).append("、");
                        otherRatioBmBuild.append(taskDistrict).append(":").append(model3.getOtherRatio1()).append("、");
                        otherRatioOmBuild.append(taskDistrict).append(":").append(model3.getOtherRatio2()).append("、");
                    }
                    List<Map<String, Object>> destorytable = toArray1(model3);
                    if(PlatformObjectUtils.isNotEmpty(destorytable)){
                        allDestorytable.addAll(destorytable);
                    }
                }

                //需紧急安置人数模型
                if (PlatformObjectUtils.isNotEmpty(intensity.getModel4Id())) {
                    String model4Type = intensity.getModel4Type();
                    if(!model4TypeList.contains(model4Type)){
                        ResettlementPersonnel model = resettlementPersonnelService.getModel1ById(intensity.getModel4Id());
                        if ("1".equals(model4Type)) {
                            modelNameList.add("需紧急安置人数默认模型");
                        }
                        if ("2".equals(model4Type)) {
                            modelNameList.add("模型管理中的模型");
                            YpgRatio ratio = new YpgRatio();
                            ratio.setIntensity("需紧急安置人数占人口比例");
                            ratio.setProvince(taskDistrict);
                            ratio.setResettlementRatio1(model.getRatio1().toString());
                            ratio.setResettlementRatio2(model.getRatio2().toString());
                            ratio.setResettlementRatio3(model.getRatio3().toString());
                            ratio.setResettlementRatio4(model.getRatio4().toString());
                            ratioList.add(ratio);
                        }
                        model4TypeList.add(model4Type);
                    }
                }
//                if (PlatformObjectUtils.isNotEmpty(intensity.getModel4Id())) {
//                    String model4Type = intensity.getModel4Type();
//                    if(!model4TypeList.contains(model4Type)){
//                        ResettlementPersonnel model = resettlementPersonnelService.getModel1ById(intensity.getModel4Id());
//                        if ("1".equals(model4Type)) {
//                            map.put("resettle1", "   根据房屋倒塌和损坏计算需转移安置人数，对于地震工作区需紧急安置人数的计算，采用国家标准《地震现场工作第4部分：灾害直接损失评估》（GB/T 18208.4-2011）算法：");
//                            map.put("resettle3", "   式中，a为户均居住面积，b为户均人口，c 为所有住宅房屋的毁坏面积，d为非简易房屋的严重破坏面积，e为非简易房屋中等破坏面积与简易房屋破坏面积之和，f为死亡人数。");
//                            map.put("resettle", "1");
//                        }
//                        if ("2".equals(model4Type)) {
//                            map.put("resettle1", "   在公里格网分布图上统计各烈度影响人口，对于需要紧急安置的人数所占比例，按下表计算：");
//                            map.put("resettle3", "                各烈度影响人口的需紧急安置人口比例");
//                            map.put("resettlementRatio1", model.getRatio1());
//                            map.put("resettlementRatio2", model.getRatio2());
//                            map.put("resettlementRatio3", model.getRatio3());
//                            map.put("resettlementRatio4", model.getRatio4());
//                            map.put("resettle", "2");
//                        }
//                        model4TypeList.add(model4Type);
//                    }
//                } else {
//                    map.put("resettle1", "");
//                    map.put("resettle3", "");
//                    map.put("resettlementRatio1", "");
//                    map.put("resettlementRatio2", "");
//                    map.put("resettlementRatio3", "");
//                    map.put("resettlementRatio4", "");
//                }

                //救援队伍,医务人员需求模型
                if (PlatformObjectUtils.isNotEmpty(intensity.getModel5Id())) {
                    RescueForceEntity rescueForceModel = rescueForceService.getModel1ById(intensity.getModel5Id());
                    if(!provinceList.contains(taskDistrict)){
                        modelNumber1Build.append(taskDistrict).append(":").append(rescueForceModel.getRescueRanksModelNumber1()).append("、");
                        modelNumber2Build.append(taskDistrict).append(":").append(rescueForceModel.getRescueRanksModelNumber2()).append("、");
                        modelNumber3Build.append(taskDistrict).append(":").append(rescueForceModel.getRescueRanksModelNumber3()).append("、");
                        modelNumber4Build.append(taskDistrict).append(":").append(rescueForceModel.getMajorRescueForceProportion()).append("%、");
                        modelNumber5Build.append(taskDistrict).append(":").append(rescueForceModel.getPopularRescueForceProportion()).append("%、");
                        modelNumber6Build.append(taskDistrict).append(":").append(rescueForceModel.getSocietyOtherForceProportion()).append("%、");
                        modelNumber7Build.append(taskDistrict).append(":").append(rescueForceModel.getMedicalStaffModelNumber()).append("、");
                        modelNumber8Build.append(taskDistrict).append(":").append(rescueForceModel.getDoctorProportion()).append("%、");
                        modelNumber9Build.append(taskDistrict).append(":").append(rescueForceModel.getNurseProportion()).append("%、");
                        modelNumber10Build.append(taskDistrict).append(":").append(rescueForceModel.getPsychologistProportion()).append("%、");
                    }
//                    map.put("modelNumber1", String.valueOf(rescueForceModel.getRescueRanksModelNumber1()));
//                    map.put("modelNumber2", String.valueOf(rescueForceModel.getRescueRanksModelNumber2()));
//                    map.put("modelNumber3", String.valueOf(rescueForceModel.getRescueRanksModelNumber3()));
//                    map.put("modelNumber4", String.valueOf(rescueForceModel.getMajorRescueForceProportion()));
//                    map.put("modelNumber5", String.valueOf(rescueForceModel.getPopularRescueForceProportion()));
//                    map.put("modelNumber6", String.valueOf(rescueForceModel.getSocietyOtherForceProportion()));
//                    map.put("modelNumber7", String.valueOf(rescueForceModel.getMedicalStaffModelNumber()));
//                    map.put("modelNumber8", String.valueOf(rescueForceModel.getDoctorProportion()));
//                    map.put("modelNumber9", String.valueOf(rescueForceModel.getNurseProportion()));
//                    map.put("modelNumber10", String.valueOf(rescueForceModel.getPsychologistProportion()));
                }
//                else {
//                    map.put("modelNumber1", "");
//                    map.put("modelNumber2", "");
//                    map.put("modelNumber3", "");
//                    map.put("modelNumber4", "");
//                    map.put("modelNumber5", "");
//                    map.put("modelNumber6", "");
//                    map.put("modelNumber7", "");
//                    map.put("modelNumber8", "");
//                    map.put("modelNumber9", "");
//                    map.put("modelNumber10", "");
//                }

                //救援物资,医疗资源需求模型sss

                if (PlatformObjectUtils.isNotEmpty(intensity.getModel6Id())) {
                    Material material = materialService.getModel1ById(intensity.getModel6Id());
                    if(!provinceList.contains(taskDistrict)){
                        modelNumber11Build.append(taskDistrict).append(":").append(material.getRatio1()).append("、");
                        modelNumber12Build.append(taskDistrict).append(":").append(material.getRatio2()).append("、");
                        modelNumber13Build.append(taskDistrict).append(":").append(material.getRatio6()).append("、");
                        modelNumber14Build.append(taskDistrict).append(":").append(material.getRatio7()).append("、");
                        modelNumber15Build.append(taskDistrict).append(":").append(material.getRatio8()).append("、");
                        modelNumber16Build.append(taskDistrict).append(":").append(material.getRatio9()).append("、");
                        modelNumber17Build.append(taskDistrict).append(":").append(material.getRatio10()).append("、");
                        modelNumber18Build.append(taskDistrict).append(":").append(material.getRatio11()).append("、");
                        modelNumber19Build.append(taskDistrict).append(":").append(material.getRatio12()).append("、");
                        modelNumber20Build.append(taskDistrict).append(":").append(material.getRatio13()).append("、");
                        modelNumber21Build.append(taskDistrict).append(":").append(material.getRatio14()).append("、");
                        modelNumber22Build.append(taskDistrict).append(":").append(material.getRatio15()).append("、");
                    }
//                    map.put("modelNumber11", String.valueOf(material.getRatio1()));
//                    map.put("modelNumber12", String.valueOf(material.getRatio2()));
//                    map.put("modelNumber13", String.valueOf(material.getRatio6()));
//                    map.put("modelNumber14", String.valueOf(material.getRatio7()));
//                    map.put("modelNumber15", String.valueOf(material.getRatio8()));
//                    map.put("modelNumber16", String.valueOf(material.getRatio9()));
//                    map.put("modelNumber17", String.valueOf(material.getRatio10()));
//                    map.put("modelNumber18", String.valueOf(material.getRatio11()));
//                    map.put("modelNumber19", String.valueOf(material.getRatio12()));
//                    map.put("modelNumber20", String.valueOf(material.getRatio13()));
//                    map.put("modelNumber21", String.valueOf(material.getRatio14()));
//                    map.put("modelNumber22", String.valueOf(material.getRatio15()));
                }
//                else {
//                    map.put("modelNumber11", "");
//                    map.put("modelNumber12", "");
//                    map.put("modelNumber13", "");
//                    map.put("modelNumber14", "");
//                    map.put("modelNumber15", "");
//                    map.put("modelNumber16", "");
//                    map.put("modelNumber17", "");
//                    map.put("modelNumber18", "");
//                    map.put("modelNumber19", "");
//                    map.put("modelNumber20", "");
//                    map.put("modelNumber21", "");
//                    map.put("modelNumber22", "");
//                }
                if(!provinceList.contains(taskDistrict)){
                    provinceList.add(taskDistrict);
                }
            }
            map.put("ratio", ratioList);
            if(!modelNameList.contains("需紧急安置人数默认模型")){
                map.put("modelName1", "需紧急安置人数默认模型(需删除)");
            }else{
                map.put("modelName1", "需紧急安置人数默认模型");
            }
            if(!modelNameList.contains("模型管理中的模型")){
                map.put("modelName2", "模型管理中的模型(需删除)");
            }else{
                map.put("modelName2", "模型管理中的模型");
            }
            map.put("deathNumber", deathNumberBuild.length()>0?deathNumberBuild.substring(0,deathNumberBuild.length()-1):"");
            map.put("injuries", injuriesBuild.length()>0?injuriesBuild.substring(0,injuriesBuild.length()-1):"");
            map.put("structureLossess", structureLossessBuild.length()>0?structureLossessBuild.substring(0,structureLossessBuild.length()-1):"");
            //建筑物室内财产经济损失评估调整参数
            map.put("indoorLossess", indoorLossessBuild.length()>0?indoorLossessBuild.substring(0,indoorLossessBuild.length()-1):"");
            //生命线经济损失评估,Bm为建筑物经济损失在总经济损失中所占百分比
            map.put("liferatioBm", liferatioBmBuild.length()>0?liferatioBmBuild.substring(0,liferatioBmBuild.length()-1):"");
            //生命线经济损失评估,Lm为生命线经济损失在总经济损失中所占百分比
            map.put("liferatioLm", liferatioLmBuild.length()>0?liferatioLmBuild.substring(0,liferatioLmBuild.length()-1):"");
            //其他经济损失评估,Bm为建筑物经济损失在总经济损失中所占百分比
            map.put("otherRatioBm", otherRatioBmBuild.length()>0?otherRatioBmBuild.substring(0,otherRatioBmBuild.length()-1):"");
            //其他经济损失评估,Om为其他经济损失在总经济损失中所占百分比
            map.put("otherRatioOm", otherRatioOmBuild.length()>0?otherRatioOmBuild.substring(0,otherRatioOmBuild.length()-1):"");
            //建筑物损失比矩阵表格
            map.put("destorytable", allDestorytable);
            map.put("modelNumber1", modelNumber1Build.length()>0?modelNumber1Build.substring(0,modelNumber1Build.length()-1):"");
            map.put("modelNumber2", modelNumber2Build.length()>0?modelNumber2Build.substring(0,modelNumber2Build.length()-1):"");
            map.put("modelNumber3", modelNumber3Build.length()>0?modelNumber3Build.substring(0,modelNumber3Build.length()-1):"");
            map.put("modelNumber4", modelNumber4Build.length()>0?modelNumber4Build.substring(0,modelNumber4Build.length()-1):"");
            map.put("modelNumber5", modelNumber5Build.length()>0?modelNumber5Build.substring(0,modelNumber5Build.length()-1):"");
            map.put("modelNumber6", modelNumber6Build.length()>0?modelNumber6Build.substring(0,modelNumber6Build.length()-1):"");
            map.put("modelNumber7", modelNumber7Build.length()>0?modelNumber7Build.substring(0,modelNumber7Build.length()-1):"");
            map.put("modelNumber8", modelNumber8Build.length()>0?modelNumber8Build.substring(0,modelNumber8Build.length()-1):"");
            map.put("modelNumber9", modelNumber9Build.length()>0?modelNumber9Build.substring(0,modelNumber9Build.length()-1):"");
            map.put("modelNumber10", modelNumber10Build.length()>0?modelNumber10Build.substring(0,modelNumber10Build.length()-1):"");
            map.put("modelNumber11", modelNumber11Build.length()>0?modelNumber11Build.substring(0,modelNumber11Build.length()-1):"");
            map.put("modelNumber12", modelNumber12Build.length()>0?modelNumber12Build.substring(0,modelNumber12Build.length()-1):"");
            map.put("modelNumber13", modelNumber13Build.length()>0?modelNumber13Build.substring(0,modelNumber13Build.length()-1):"");
            map.put("modelNumber14", modelNumber14Build.length()>0?modelNumber14Build.substring(0,modelNumber14Build.length()-1):"");
            map.put("modelNumber15", modelNumber15Build.length()>0?modelNumber15Build.substring(0,modelNumber15Build.length()-1):"");
            map.put("modelNumber16", modelNumber16Build.length()>0?modelNumber16Build.substring(0,modelNumber16Build.length()-1):"");
            map.put("modelNumber17", modelNumber17Build.length()>0?modelNumber17Build.substring(0,modelNumber17Build.length()-1):"");
            map.put("modelNumber18", modelNumber18Build.length()>0?modelNumber18Build.substring(0,modelNumber18Build.length()-1):"");
            map.put("modelNumber19", modelNumber19Build.length()>0?modelNumber19Build.substring(0,modelNumber19Build.length()-1):"");
            map.put("modelNumber20", modelNumber20Build.length()>0?modelNumber20Build.substring(0,modelNumber20Build.length()-1):"");
            map.put("modelNumber21", modelNumber21Build.length()>0?modelNumber21Build.substring(0,modelNumber21Build.length()-1):"");
            map.put("modelNumber22", modelNumber22Build.length()>0?modelNumber22Build.substring(0,modelNumber22Build.length()-1):"");
            StringBuilder stringBuilder1 = new StringBuilder();
            //没有破裂尺度
            List<String> list1 = new ArrayList<>();
            if (preAssessTaskEntitys1.size()!=0){
                int s = 0;
                for (PreAssessTaskEntity preAssessTaskEntity : preAssessTaskEntitys1) {
                    //任务地区
                    String taskDistrict = preAssessTaskEntity.getTaskDistrict();
                    String province = taskDistrict.split("-")[0];
                    SeismicIntensityRelation intensity = intensityRelationRepository.getByTaskId(preAssessTaskEntity.getId());
                    IntensityAttenuation model1 = intensityAttenuationService.getModel1ById(intensity.getModel1Id());
                    if(model1!=null){
                        if(!list1.contains(province+"-"+model1.getId())){
                            String a = "Ia = " + model1.getLongRatio1() + "+" + model1.getLongRatio2() + "M -" + model1.getLongRatio3() + model1.getLongSymbol() + "(Ra+" + model1.getLongRatio4() + ")";
                            String b = "Ib = " + model1.getShortRatio1() + "+" + model1.getShortRatio2() + "M -" + model1.getShortRatio3() + model1.getShortSymbol() + "(Rb+" + model1.getShortRatio4() + ")";
                            String ss="";
                            if (s != 0){
                                ss="";
                            }
                            stringBuilder1.append(ss+taskDistrict+":\n");
                            stringBuilder1.append("                "+a+"\n");
                            stringBuilder1.append("                "+b+"\n");
                            list1.add(province+"-"+model1.getId());
                        }
                    }
                }
                stringBuilder1.append("   其中Ia、Ib分别为长短轴烈度，M为震级，Ra、Rb分别为烈度为 I 时长、短半轴的长度。\n");
            }
            list1 = new ArrayList<>();
            if (preAssessTaskEntitys2.size()!=0){
                String q="";
                if (stringBuilder1.toString().length()!=0){
                    q="    ";
                }
                stringBuilder1.append(q+"当震级小于7.0级时使用椭圆衰减模型，当震级大于等于7.0级时使用破裂尺度公式计算出长轴长度，根据长短轴比例计算出短轴长度。\n");
                stringBuilder1.append("  1、当震级小于7.0级时使用椭圆衰减模型\n");
                StringBuilder stringBuilder2 = new StringBuilder();
                StringBuilder stringBuilder3 = new StringBuilder();
                for (PreAssessTaskEntity preAssessTaskEntity : preAssessTaskEntitys2) {
                    //任务地区
                    String taskDistrict = preAssessTaskEntity.getTaskDistrict();
                    String province = taskDistrict.split("-")[0];
                    SeismicIntensityRelation intensity = intensityRelationRepository.getByTaskId(preAssessTaskEntity.getId());
                    IntensityAttenuation model1 = intensityAttenuationService.getModel1ById(intensity.getModel1Id());
                    if(model1!=null){
                        if(!list1.contains(province+"-"+model1.getId())){
                            String a = "Ia = " + model1.getLongRatio1() + "+" + model1.getLongRatio2() + "M -" + model1.getLongRatio3() + model1.getLongSymbol() + "(Ra+" + model1.getLongRatio4() + ")";
                            String b = "Ib = " + model1.getShortRatio1() + "+" + model1.getShortRatio2() + "M -" + model1.getShortRatio3() + model1.getShortSymbol() + "(Rb+" + model1.getShortRatio4() + ")";
                            String c = "M = "+model1.getFormulaRatio1()+ "+" +model1.getFormulaRatio2()+ "* log(SRL)";
                            String d = String.valueOf(model1.getScale());
                            stringBuilder1.append("  "+taskDistrict+":\n");
                            stringBuilder1.append("                "+a+"\n");
                            stringBuilder1.append("                "+b+"\n");
                            stringBuilder2.append("    "+taskDistrict+":\n");
                            stringBuilder2.append("                  "+c+"\n");
                            stringBuilder3.append(d).append(",");
                            list1.add(province+"-"+model1.getId());
                        }
                    }
                }
                stringBuilder1.append("    其中Ia、Ib分别为长短轴烈度，M为震级，Ra、Rb分别为烈度为 I 时长、短半轴的长度。\n");
                stringBuilder1.append("  2、当震级大于等于7.0级时使用破裂尺度公式计算出长轴长度，根据长短轴比例计算出短轴长度\n");
                stringBuilder1.append("    破裂尺度公式:\n");
                stringBuilder1.append(stringBuilder2);
                stringBuilder1.append("    SRL为地表破裂带长度\n");
                stringBuilder1.append("    最终的长轴长度=Ra * 2 +SRL\n");
                stringBuilder1.append("    长短轴比例:"+stringBuilder3.toString().substring(0,stringBuilder3.toString().length()-1)+"\n");
            }
            map.put("intensity", stringBuilder1.toString());
        }

        if(PlatformObjectUtils.isEmpty(taskIdList)){
            taskIdList = Arrays.asList(id);
        }
        List<ResultMainEntity> resultMainEntities = resultTotalRepository.getResultTotalByTaskId(taskIdList);
        List<ResultTable> resultTables=toLists(resultMainEntities);
        map.put("tables", resultTables);
        return map;
    }

    private List<ResultTable> toLists(List<ResultMainEntity> resultMainEntities) {
        List<ResultTable> resultTables = new ArrayList<>();
        for (ResultMainEntity resultMainEntity : resultMainEntities) {
            ResultTable resultTable = new ResultTable();
            BeanUtil.copyPropertiesIgnoreEmpty(resultMainEntity,resultTable);
            String deathTollAfter = resultTable.getDeathTollAfter();
            if(StringUtils.isNotBlank(deathTollAfter) && deathTollAfter.contains("-") && deathTollAfter.split("-")[0].equals(deathTollAfter.split("-")[1])){
                deathTollAfter = deathTollAfter.split("-")[0];
                resultTable.setDeathTollAfter(deathTollAfter);
            }
            String injuredNumAfter = resultTable.getInjuredNumAfter();
            if(StringUtils.isNotBlank(injuredNumAfter) && injuredNumAfter.contains("-") && injuredNumAfter.split("-")[0].equals(injuredNumAfter.split("-")[1])){
                injuredNumAfter = injuredNumAfter.split("-")[0];
                resultTable.setInjuredNumAfter(injuredNumAfter);
            }
            resultTable.setLatitude(new BigDecimal(resultMainEntity.getLatitude()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            resultTable.setLongitude(new BigDecimal(resultMainEntity.getLongitude()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            resultTables.add(resultTable);
        }
        return resultTables;
    }

    private List<Map<String, Object>> toArray1(EconomicLosses model3) {
        List<Object> list1 = Arrays.asList(model3.getProvince(),"高层建筑", model3.getHighBasicIntact(), model3.getHighSlightDamage(), model3.getHighMidDamage(), model3.getHighBadDamage(), model3.getHighDestory());
        List<Object> list2 = Arrays.asList(model3.getProvince(),"钢结构", model3.getSteelBasicIntact(), model3.getSteelSlightIntact(), model3.getSteelMidIntact(), model3.getSteelBadIntact(), model3.getSteelDestory());
        List<Object> list3 = Arrays.asList(model3.getProvince(),"多层钢筋混凝土结构", model3.getMultipleBasicIntact(), model3.getMultipleSlightIntact(), model3.getMultipleMidIntact(), model3.getMultipleBadIntact(), model3.getMultipleDestory());
        List<Object> list4 = Arrays.asList(model3.getProvince(),"砖混结构", model3.getBrickConcreteBasicIntact(), model3.getBrickConcreteSlightIntact(), model3.getBrickConcreteMidIntact(), model3.getBrickConcreteBadIntact(), model3.getBrickConcreteDestory());
        List<Object> list5 = Arrays.asList(model3.getProvince(),"砖木结构", model3.getBrickWoodBasicIntact(), model3.getBrickWoodSlightIntact(), model3.getBrickWoodMidIntact(), model3.getBrickWoodBadIntact(), model3.getBrickWoodDestory());
        List<Object> list6 = Arrays.asList(model3.getProvince(),"土结构", model3.getSoilBasicIntact(), model3.getSoilSlightIntact(), model3.getSoilMidIntact(), model3.getSoilBadIntact(), model3.getSoilDestory());
        List<Object> list7 = Arrays.asList(model3.getProvince(),"木结构", model3.getWoodBasicIntact(), model3.getWoodSlightIntact(), model3.getWoodMidIntact(), model3.getWoodBadIntact(), model3.getWoodDestory());
        List<Object> list8 = Arrays.asList(model3.getProvince(),"石结构", model3.getStoneBasicIntact(), model3.getStoneSlightIntact(), model3.getStoneMidIntact(), model3.getStoneBadIntact(), model3.getStoneDestory());
        List<Object> list9 = Arrays.asList(model3.getProvince(),"其他结构", model3.getOtherBasicIntact(), model3.getOtherSlightIntact(), model3.getOtherMidIntact(), model3.getOtherBadIntact(), model3.getOtherDestory());
        List<List<Object>> bigDecimals = Arrays.asList(list1, list2, list3, list4, list5, list6, list7, list8, list9);
        List<Map<String, Object>> destorytable = new ArrayList<>();
        for (List<Object> bigDecimal : bigDecimals) {
            Map<String, Object> map = new HashMap<>();
            map.put("province", bigDecimal.get(0).toString());
            map.put("type", bigDecimal.get(1).toString());
            map.put("ratio1", bigDecimal.get(2).toString());
            map.put("ratio2", bigDecimal.get(3).toString());
            map.put("ratio3", bigDecimal.get(4).toString());
            map.put("ratio4", bigDecimal.get(5).toString());
            map.put("ratio5", bigDecimal.get(6).toString());
            destorytable.add(map);
        }
        return destorytable;
    }

    private static String numberToChinese(int number) {
        String[] numbers = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        String[] units = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十"};
        String sign = number < 0 ? "负" : "";
        if (number < 0) {
            number = -number;
        }
        StringBuilder result = new StringBuilder(sign);
        String string = String.valueOf(number);
        int n = string.length();
        char[] numberCharArray = string.toCharArray();
        for (int i = 0; i < n; i++) {
            int digNum = n - i; // 位数
            int num = numberCharArray[i] - '0';
            if (num != 0) {
                result.append(numbers[num]).append(units[digNum - 1]);
                continue;
            }

            if (result.toString().endsWith(numbers[0])) {
                // 如果是单位所在的位数，则去除上一个0，加上单位
                if (digNum % 4 == 1) {
                    result.deleteCharAt(result.length() - 1);
                    result.append(units[digNum - 1]);
                }
            } else {
                result.append(numbers[0]);
            }
        }
        return result.toString();
    }

    @Override
    public Map<String, Map<String, List<Object[]>>> getAreaResultList(String taskId, String tab,List<String> taskIdList) {
        Map<String, Map<String, List<Object[]>>> mapMap = new HashMap<>();
        Map<String, List<Object[]>> listMap1 = null;
        Map<String, List<Object[]>> listMap2 = null;
        Map<String, List<Object[]>> listMap3 = null;
        mapMap.put("1", new HashMap<>());
        mapMap.put("2", new HashMap<>());
        mapMap.put("3", new HashMap<>());
        List<ResultMainEntity> resultMainEntities = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(taskIdList)){
            List<ResultMainEntity> tempResult = resultTotalRepository.getResultTotalByTaskId(taskIdList);
            if(PlatformObjectUtils.isNotEmpty(tempResult) && tempResult.size()>0){
                resultMainEntities.addAll(tempResult);
            }
        }else{
            resultMainEntities = resultTotalRepository.getResultTotalByTaskId(taskId);
        }

        String division = null;
        Table<String,String,String> table1 =  HashBasedTable.create();
        Table<String,BigDecimal,String> table2 =  HashBasedTable.create();
        Table<String,String,String> table3 =  HashBasedTable.create();
        for (ResultMainEntity entity : resultMainEntities) {
            String macroPosition = entity.getMacroPosition();
            if ("1".equals(tab)) {
                //地市
                String[] split = macroPosition.split(",");
                //division = macroPosition.substring(0, macroPosition.indexOf(",", macroPosition.indexOf(",") + 1));
                division = split[1];
            } else if ("2".equals(tab)) {
                //区县
                division = macroPosition;
                String[] split = macroPosition.split(",");
                if (split.length == 3) {
                    division = macroPosition.substring(macroPosition.lastIndexOf(",")+1);
                }
                if (split.length == 4) {
                    division = split[2];
                }
            }
            //3.3人员伤亡
            try {
                Map<String, String> row = table1.row(division + "-" + entity.getMagnitude());
                if(entity.getMagnitude().compareTo(BigDecimal.valueOf(6.6))==0){
                    System.out.println("111");
                }
                if (PlatformObjectUtils.isNotEmpty(row)) {
                    String finalDivision = division;
                    row.forEach((k, v) -> {
                        String tempKey = k;
                        if (StringUtils.isNotBlank(entity.getDeathTollAfter())) {
                            String newDeath = entity.getDeathTollAfter();
                            BigDecimal newPre = BigDecimal.ZERO;
                            BigDecimal newPost = BigDecimal.ZERO;
                            if (newDeath.contains("-")) {
                                newPre = new BigDecimal(newDeath.split("-")[0]);
                                newPost = new BigDecimal(newDeath.split("-")[1]);
                            } else {
                                newPost = new BigDecimal(newDeath);
                            }
                            BigDecimal oldPre = BigDecimal.ZERO;
                            BigDecimal oldPost = BigDecimal.ZERO;
                            if(StringUtils.isNotBlank(k)){
                                if (k.contains("-")) {
                                    oldPre = new BigDecimal(k.split("-")[0]);
                                    oldPost = new BigDecimal(k.split("-")[1]);
                                } else {
                                    oldPost = StringUtils.isBlank(k)?BigDecimal.ZERO:new BigDecimal(k);
                                }
                            }
                            BigDecimal pre = oldPre.add(newPre);
                            BigDecimal post = oldPost.add(newPost);
                            k = (pre + "-" + post);
                        }
                        if (StringUtils.isNotBlank(entity.getInjuredNumAfter())) {
                            String newInjure = entity.getInjuredNumAfter();
                            BigDecimal newPre = BigDecimal.ZERO;
                            BigDecimal newPost = BigDecimal.ZERO;
                            if (newInjure.contains("-")) {
                                newPre = new BigDecimal(newInjure.split("-")[0]);
                                newPost = new BigDecimal(newInjure.split("-")[1]);
                            } else {
                                newPost = new BigDecimal(newInjure);
                            }

                            BigDecimal oldPre = BigDecimal.ZERO;
                            BigDecimal oldPost = BigDecimal.ZERO;
                            if (v.contains("-")) {
                                oldPre = new BigDecimal(v.split("-")[0]);
                                oldPost = new BigDecimal(v.split("-")[1]);
                            } else {
                                oldPost = StringUtils.isBlank(v)?BigDecimal.ZERO:new BigDecimal(v);
                            }
                            BigDecimal pre = oldPre.add(newPre);
                            BigDecimal post = oldPost.add(newPost);
                            v = (pre + "-" + post);
                        }
                        table1.remove(finalDivision + "-" + entity.getMagnitude(),tempKey);
                        table1.put(finalDivision + "-" + entity.getMagnitude(), k, v);
                    });
                } else {
                    String deathTollAfter = StringUtils.isNotBlank(entity.getDeathTollAfter())?entity.getDeathTollAfter():"";
                    if (StringUtils.isNotBlank(deathTollAfter) && !deathTollAfter.contains("-")) {
                        deathTollAfter = "0-" + deathTollAfter;
                    }
                    String injuredNumAfter = StringUtils.isNotBlank(entity.getInjuredNumAfter())?entity.getInjuredNumAfter():"";
                    if (StringUtils.isNotBlank(injuredNumAfter) && !injuredNumAfter.contains("-")) {
                        injuredNumAfter = "0-" + injuredNumAfter;
                    }
                    table1.put(division + "-" + entity.getMagnitude(), deathTollAfter, injuredNumAfter);
                }

                //3.4 需紧急安置人数
                String oldResettledNumAfter = table2.get(division, entity.getMagnitude());
                if (PlatformObjectUtils.isNotEmpty(oldResettledNumAfter)) {
                    if (StringUtils.isNotBlank(entity.getResettledNumAfter())) {
                        String newResettled = entity.getResettledNumAfter();
                        BigDecimal newPre = BigDecimal.ZERO;
                        BigDecimal newPost = BigDecimal.ZERO;
                        if (newResettled.contains("-")) {
                            newPre = new BigDecimal(newResettled.split("-")[0]);
                            newPost = new BigDecimal(newResettled.split("-")[1]);
                        } else {
                            newPost = new BigDecimal(newResettled);
                        }

                        BigDecimal oldPre = BigDecimal.ZERO;
                        BigDecimal oldPost = BigDecimal.ZERO;
                        if (oldResettledNumAfter.contains("-")) {
                            oldPre = new BigDecimal(oldResettledNumAfter.split("-")[0]);
                            oldPost = new BigDecimal(oldResettledNumAfter.split("-")[1]);
                        } else {
                            oldPost = StringUtils.isBlank(oldResettledNumAfter)?BigDecimal.ZERO:new BigDecimal(oldResettledNumAfter);
                        }
                        BigDecimal pre = oldPre.add(newPre);
                        BigDecimal post = oldPost.add(newPost);
                        oldResettledNumAfter = (pre + "-" + post);
                    }
                    table2.remove(division, entity.getMagnitude());
                    table2.put(division, entity.getMagnitude(), oldResettledNumAfter);
                } else {
                    String resettledNumAfter = StringUtils.isNotBlank(entity.getResettledNumAfter())?entity.getResettledNumAfter():"";
                    if (StringUtils.isNotBlank(resettledNumAfter) && !resettledNumAfter.contains("-")) {
                        resettledNumAfter = "0-" + resettledNumAfter;
                    }
                    table2.put(division, entity.getMagnitude(), resettledNumAfter);
                }
                //3.5 救援力量
                Map<String, String> row3 = table3.row(division + "-" + entity.getMagnitude());
                if (PlatformObjectUtils.isNotEmpty(row3)) {
                    String finalDivision = division;
                    row3.forEach((k, v) -> {
                        String tempKey = k;
                        if (StringUtils.isNotBlank(entity.getRescueForceAfter())) {
                            String newForce = entity.getRescueForceAfter();
                            BigDecimal newPre = BigDecimal.ZERO;
                            BigDecimal newPost = BigDecimal.ZERO;
                            if (newForce.contains("-")) {
                                newPre = new BigDecimal(newForce.split("-")[0]);
                                newPost = new BigDecimal(newForce.split("-")[1]);
                            } else {
                                newPost = new BigDecimal(newForce);
                            }

                            BigDecimal oldPre = BigDecimal.ZERO;
                            BigDecimal oldPost = BigDecimal.ZERO;
                            if (k.contains("-")) {
                                oldPre = new BigDecimal(k.split("-")[0]);
                                oldPost = new BigDecimal(k.split("-")[1]);
                            } else {
                                oldPost = StringUtils.isBlank(k)?BigDecimal.ZERO:new BigDecimal(k);
                            }
                            BigDecimal pre = oldPre.add(newPre);
                            BigDecimal post = oldPost.add(newPost);
                            k = (pre + "-" + post);
                        }
                        if (StringUtils.isNotBlank(entity.getTentNumAfter())) {
                            String newTentNum = entity.getTentNumAfter();
                            BigDecimal newPre = BigDecimal.ZERO;
                            BigDecimal newPost = BigDecimal.ZERO;
                            if (newTentNum.contains("-")) {
                                newPre = new BigDecimal(newTentNum.split("-")[0]);
                                newPost = new BigDecimal(newTentNum.split("-")[1]);
                            } else {
                                newPost = new BigDecimal(newTentNum);
                            }

                            BigDecimal oldPre = BigDecimal.ZERO;
                            BigDecimal oldPost = BigDecimal.ZERO;
                            if (v.contains("-")) {
                                oldPre = new BigDecimal(v.split("-")[0]);
                                oldPost = new BigDecimal(v.split("-")[1]);
                            } else {
                                oldPost = oldPost = StringUtils.isBlank(v)?BigDecimal.ZERO:new BigDecimal(v);
                            }
                            BigDecimal pre = oldPre.add(newPre);
                            BigDecimal post = oldPost.add(newPost);
                            v = (pre + "-" + post);
                        }
                        table3.remove(finalDivision + "-" + entity.getMagnitude(),tempKey);
                        table3.put(finalDivision + "-" + entity.getMagnitude(), k, v);
                    });
                } else {
                    String rescueForceAfter = StringUtils.isNotBlank(entity.getRescueForceAfter())?entity.getRescueForceAfter():"";
                    if (StringUtils.isNotBlank(rescueForceAfter) && !rescueForceAfter.contains("-")) {
                        rescueForceAfter = "0-" + rescueForceAfter;
                    }
                    String tentNumAfter = StringUtils.isNotBlank(entity.getTentNumAfter())?entity.getTentNumAfter():"";
                    if (StringUtils.isNotBlank(tentNumAfter) && !tentNumAfter.contains("-")) {
                        tentNumAfter = "0-" + tentNumAfter;
                    }
                    table3.put(division + "-" + entity.getMagnitude(), rescueForceAfter, tentNumAfter);
                }
            }catch (ConcurrentModificationException e){

            }
        }
        listMap1 = new HashMap<>();
        List<Object[]> newList = null;
        Map<String, Map<String, String>> stringMapMap1 = table1.rowMap();
        Map<String, Map<String, String>> result = new LinkedHashMap<>();
        stringMapMap1.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        Iterator<Map.Entry<String, Map<String, String>>> iterator = result.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String, Map<String, String>> next = iterator.next();
            String k = next.getKey();
            String distirct = k.split("-")[0];
            if(listMap1.containsKey(distirct)){
                newList = listMap1.get(distirct);
            }else{
                newList = new ArrayList<>();
            }
            String magnitude = k.split("-")[1];
            Map<String, String> value = next.getValue();
            Iterator<Map.Entry<String, String>> iterator1 = value.entrySet().iterator();
            Object[] objects11 = new Object[3];
            while(iterator1.hasNext()){
                Map.Entry<String, String> next1 = iterator1.next();
                String key = next1.getKey();
                String v = next1.getValue();
                objects11[0] = magnitude;
                try{
                    objects11[1] = StringUtils.isNotBlank(key)?(key.split("-")[0].equals(key.split("-")[1])?key.split("-")[0]:key):"";
                    objects11[2] = StringUtils.isNotBlank(v)?(v.split("-")[0].equals(v.split("-")[1])?v.split("-")[0]:v):"";
                }catch (ArrayIndexOutOfBoundsException ex){
                    ex.printStackTrace();
                }

            }
            newList.add(objects11);
            listMap1.put(distirct, newList);
        }
        mapMap.put("1", listMap1);
        listMap2 = new HashMap<>();
        newList = null;
        Map<String, Map<BigDecimal, String>> stringMapMap2 = table2.rowMap();
        Map<String, Map<BigDecimal, String>> result1 = new LinkedHashMap<>();
        stringMapMap2.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result1.put(x.getKey(), x.getValue()));
        Iterator<Map.Entry<String, Map<BigDecimal, String>>> iterator2 = result1.entrySet().iterator();
        while(iterator2.hasNext()){
            Map.Entry<String, Map<BigDecimal, String>> next = iterator2.next();
            String distirct = next.getKey();
            if(listMap2.containsKey(distirct)){
                newList = listMap2.get(distirct);
            }else{
                newList = new ArrayList<>();
            }
            Map<BigDecimal, String> value = next.getValue();
            Iterator<Map.Entry<BigDecimal, String>> iterator1 = value.entrySet().iterator();
            while(iterator1.hasNext()){
                Object[] objects11 = new Object[2];
                Map.Entry<BigDecimal, String> next1 = iterator1.next();
                //震级
                BigDecimal magnitude = next1.getKey();
                //安置人数
                String v = next1.getValue();
                objects11[0] = magnitude;
                objects11[1] = StringUtils.isNotBlank(v)?(v.split("-")[0].equals(v.split("-")[1])?v.split("-")[0]:v):"";
                newList.add(objects11);
            }
            //todo 要测试
            newList.sort(new Comparator<Object[]>() {
                @Override
                public int compare(Object[] o1, Object[] o2) {
                    if (Double.parseDouble(o1[0].toString()) > Double.parseDouble(o2[0].toString())) {
                        return 1;
                    }
                    return -1;
                }
            });
            listMap2.put(distirct, newList);
        }
        mapMap.put("2", listMap2);
        listMap3 = new HashMap<>();
        newList = null;
        Map<String, Map<String, String>> stringMapMap3 = table3.rowMap();
        Map<String, Map<String, String>> result2 = new LinkedHashMap<>();
        stringMapMap3.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
        Iterator<Map.Entry<String, Map<String, String>>> iterator3 = result2.entrySet().iterator();
        while(iterator3.hasNext()){
            Map.Entry<String, Map<String, String>> next = iterator3.next();
            String k = next.getKey();
            String distirct = k.split("-")[0];
            if(listMap3.containsKey(distirct)){
                newList = listMap3.get(distirct);
            }else{
                newList = new ArrayList<>();
            }
            String magnitude = k.split("-")[1];
            Map<String, String> value = next.getValue();
            Iterator<Map.Entry<String, String>> iterator1 = value.entrySet().iterator();
            Object[] objects11 = new Object[3];
            while(iterator1.hasNext()){
                Map.Entry<String, String> next1 = iterator1.next();
                String key = next1.getKey();
                String v = next1.getValue();
                objects11[0] = magnitude;
                objects11[1] = StringUtils.isNotBlank(key)?(key.split("-")[0].equals(key.split("-")[1])?key.split("-")[0]:key):"";
                objects11[2] = StringUtils.isNotBlank(v)?(v.split("-")[0].equals(v.split("-")[1])?v.split("-")[0]:v):"";
            }
            newList.add(objects11);
            listMap3.put(distirct, newList);
        }
        mapMap.put("3", listMap3);
        return mapMap;
    }

    private String compareTo(String num1, String num2) {
        // num1:10-0
        // num2: 6 11  4-9 11-15 5-24

        // num1:4-8
        // num2: 2 6 11  2-3 11-15 5-24 2-6
        String[] split1 = StringUtils.isBlank(num1)?new String[0]:num1.split("-");
        //5 10
        String[] split2 = StringUtils.isBlank(num2)?new String[0]:num2.split("-");//5 10
        for (int i = 0; i < split1.length; i++) {
            if (split2.length == 1) {
                if (i == 0 && new BigDecimal(split2[0]).compareTo(new BigDecimal(split1[0])) < 0) {
                    if (split1.length == 2) {
                        if (new BigDecimal(split1[0]).compareTo(new BigDecimal(split1[1])) > 0) {
                            split1[1] = String.valueOf(new BigDecimal(split1[0]).intValue());
                            split1[0] = String.valueOf(new BigDecimal(split2[0]).intValue());
                        } else {
                            split1[0] = String.valueOf(new BigDecimal(split2[0]).intValue());
                            split1[1] = String.valueOf(new BigDecimal(split1[1]).intValue());
                        }
                    } else {
                        split1[0] = String.valueOf(new BigDecimal(split2[0]).intValue());
                        split1[1] = String.valueOf(new BigDecimal(split1[1]).intValue());
                    }
                } else if (i == 1 && new BigDecimal(split2[0]).compareTo(new BigDecimal(split1[1])) > 0) {
                    split1[0] = String.valueOf(new BigDecimal(split1[0]).intValue());
                    split1[1] = String.valueOf(new BigDecimal(split2[0]).intValue());
                }
            } else {
                if (i == 0 && new BigDecimal(split2[0]).compareTo(new BigDecimal(split1[0])) < 0) {
                    if (split1.length == 2) {
                        if (new BigDecimal(split1[0]).compareTo(new BigDecimal(split1[1])) > 0) {
                            split1[1] = String.valueOf(new BigDecimal(split1[0]).intValue());
                            split1[0] = String.valueOf(new BigDecimal(split2[0]).intValue());
                        } else {
                            split1[0] = String.valueOf(new BigDecimal(split2[0]).intValue());
                            split1[1] = String.valueOf(new BigDecimal(split1[1]).intValue());
                        }
                    } else {
                        split1[0] = String.valueOf(new BigDecimal(split2[0]).intValue());
                        split1[1] = String.valueOf(new BigDecimal(split1[1]).intValue());
                    }
                } else if (i == 1 && new BigDecimal(split2[1]).compareTo(new BigDecimal(split1[1])) > 0) {
                    split1[0] = String.valueOf(new BigDecimal(split1[0]).intValue());
                    split1[1] = String.valueOf(new BigDecimal(split2[0]).intValue());
                }
            }

        }
        if(split1.length>1){
            num2 = split1[0] + "-" + split1[1];
        }else if(split1.length==1){
            num2 = split1[0] ;
        }else{
            num2 = "";
        }

        return num2;
    }

}
